package com.xjwlmq.dx.servlet;

import com.alibaba.fastjson.JSON;
import com.xjwlmq.dx.dao.impl.StudentDaoImpl;
import com.xjwlmq.dx.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName StudentAddServlet
 * @Description TODO:
 * @Author 12994
 * @Date 2024/9/30 12:09
 * @Version 1.0
 **/
@WebServlet("/userUpdate")
public class StudentUpdateServlet extends HttpServlet {
    StudentDaoImpl studentDao = new StudentDaoImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // super.service(req, resp);
        // 设置响应编码格式
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html:charset=UTF-8");
        // 设置跨域响应头（解决跨域问题）
        resp.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有源
        resp.setHeader("Access-Control-Allow-Methods", "POST, DELETE, PUT, OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");

        /*
         * 根据添加一个用户
         * req.getParameter();从get url中提取参数
         * Integer.getInteger; 从字符串转Int
         */
        Student student = new Student();
        student.setAddress(req.getParameter("address"));
        student.setBornDate(req.getParameter("bornDate"));
        student.setEmail(req.getParameter("email"));
        student.setGradeId(Integer.parseInt(req.getParameter("gradeId")));
        student.setIdentityCard(req.getParameter("identityCard"));
        student.setLoginPwd(req.getParameter("loginPwd"));
        student.setPhone(req.getParameter("phone"));
        student.setStudentName(req.getParameter("studentName"));
        student.setSex(Integer.parseInt(req.getParameter("sex")));
        student.setStudentNo(Integer.parseInt(req.getParameter("studentNo")));

        int cont = studentDao.updateStudentViaStudentNo(student.getStudentNo(), student);
        if (cont > 0) {
            resp.getWriter().write(JSON.toJSONString("修改了%d行数据.".formatted(cont)));
        } else {
            resp.getWriter().write(JSON.toJSONString("没有影响数据..."));
        }
    }
}
